import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 何杰
 * @version 1.0
 */
public class threeSum {
    public static void main(String[] args) {
        //-1,0,1,2,-1,-4
        int[] test = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> res = threeSum(test);
        res.forEach(list -> System.out.println(list));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i-1]) {
                continue;
            }
            int left = i+1, right = nums.length - 1;
            int target = -nums[i];
            while(left < right) {
                int sum = nums[left] + nums[right];
                if(sum == target) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                } else if(sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }
}
